package com.flow.asyncflow.core.utils.msg;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import com.flow.asyncflow.core.entity.config.AsyncFlowInfo;
import com.flow.asyncflow.core.entity.core.AsyncFlowRequest;
import com.flow.asyncflow.core.entity.log.asyncflowlog.AsyncFlowExecutionMethodEntity;
import com.flow.asyncflow.core.utils.common.UtilsCommon;
import com.flow.asyncflow.core.utils.configuration.AsyncFlowConfiguration;
import com.flow.asyncflow.core.utils.http.AsyncFlowHttpClientUtil;

import lombok.Data;
import org.apache.commons.lang.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;


public class AsyncFlowSendMsg {


    /**
     * 发送企业微信
     *
     * @param users   接收人工号，多个接收者用‘|’分隔，最多支持100个
     * @param content 内容，（企业微信最长不超过2048个字节）
     */
    public static void sendQYWXMsg(String users, String content, String sendUrl) {

        if (StringUtils.isBlank(sendUrl)) {
            return;
        }
        SendMsgReqRequest sendMsgReqRequest = new SendMsgReqRequest();
        sendMsgReqRequest.setUsers(users);
        sendMsgReqRequest.setContent(content);
        String result = AsyncFlowHttpClientUtil.post(sendUrl,sendMsgReqRequest);
    }

    /**
     * 发送企业微信
     *
     * @param users   接收人工号，多个接收者用‘|’分隔，最多支持100个
     * @param content 内容，（企业微信最长不超过2048个字节）
     */
    public static void sendQYWXMsg(String users, String content) {

        String sendUrl = new AsyncFlowConfiguration().getNodeArmUrl();
        if (StringUtils.isBlank(sendUrl)) {
            return;
        }
        SendMsgReqRequest sendMsgReqRequest = new SendMsgReqRequest();
        sendMsgReqRequest.setUsers(users);
        sendMsgReqRequest.setContent(content);
        String result = AsyncFlowHttpClientUtil.post(sendUrl,sendMsgReqRequest);
    }

    /**
     * 发送业务报警【发送给开发】
     *
     * @param asyncFlowRequest 请求参数
     * @param resMsg           返回描述
     * @param fileName         文件名
     * @param asyncFlowInfo    报警工号
     */
    public static void sendAlarmMsg(AsyncFlowRequest asyncFlowRequest, String resMsg, String fileName, AsyncFlowInfo asyncFlowInfo) {
        String serialid = asyncFlowRequest.getBusinessSerialId();

        if (StringUtils.isBlank(serialid)) {

            String dateGuid = LocalDateTimeUtil.format(asyncFlowRequest.getRequesterTime(), DatePattern.PURE_DATETIME_PATTERN);
            serialid = asyncFlowRequest.getReqTypeEnumMsg() + "-" + dateGuid;
        }
        StringBuilder stringBuilder;
        stringBuilder = new StringBuilder();
        stringBuilder.append("【业务报警】")
                .append("\n节点：").append(asyncFlowRequest.getReqTypeEnumName()).append("--").append(asyncFlowRequest.getReqTypeEnumMsg())
                .append("\n来源：").append(asyncFlowRequest.getSourceDes())
                .append("\n位置：").append(fileName)
                .append("\n单号：").append(serialid)
                .append("\n时间：").append(LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.NORM_DATETIME_PATTERN))
                .append("\n环境：").append(asyncFlowInfo.getEvn())
                .append("\n错误：").append(resMsg)
                .append("\n请求：").append(JSON.toJSONString(asyncFlowRequest));
        sendQYWXMsg(asyncFlowInfo.getFlowMaintainName(), stringBuilder.toString(), asyncFlowInfo.getNodeArmUrl());
    }

    /**
     * 发送业务报警【发送给业务】
     *
     * @param asyncFlowRequest 请求参数
     * @param resMsg           返回描述
     * @param asyncFlowInfo    报警工号
     */
    public static void sendBusinessAlarmMsg(AsyncFlowRequest asyncFlowRequest, String resMsg, Object obj, AsyncFlowInfo asyncFlowInfo) {

        if (StringUtils.isBlank(asyncFlowRequest.getBusinessSerialId())) {

            return;
        }
        AsyncFlowExecutionMethodEntity asyncFlowExecutionMethodEntity = UtilsCommon.getLogMethodName(obj);
        SendBusinessAlarmRequest sendBusinessAlarmRequest = new SendBusinessAlarmRequest();
        sendBusinessAlarmRequest.setAlarmMsg(resMsg);
        sendBusinessAlarmRequest.setBusinessSerialId(asyncFlowRequest.getBusinessSerialId());
        sendBusinessAlarmRequest.setAsyncFlowModuleName(asyncFlowRequest.getReqTypeEnumName());
        sendBusinessAlarmRequest.setAsyncFlowNodeName(asyncFlowRequest.getReqTypeEnumMsg());
        sendBusinessAlarmRequest.setExecuteNodeName(asyncFlowExecutionMethodEntity.getLogMethodName());
        String result = AsyncFlowHttpClientUtil.post(asyncFlowInfo.getBusinessArmUrl(), sendBusinessAlarmRequest);

    }

    public static String buildErrorMsg(AsyncFlowRequest asyncFlowRequest, Exception exception, String exeName, AsyncFlowInfo asyncFlowInfo) {

        StringBuilder stringBuilder = new StringBuilder();
        String serialid = asyncFlowRequest.getBusinessSerialId();

        if (StringUtils.isBlank(serialid)) {
            String dateGuid = LocalDateTimeUtil.format(asyncFlowRequest.getRequesterTime(), DatePattern.PURE_DATETIME_PATTERN);

            serialid = asyncFlowRequest.getReqTypeEnumMsg() + "-" + dateGuid;
        }

        stringBuilder.append("【节点异常报警】")
                .append("\n节点：").append(asyncFlowRequest.getReqTypeEnumName()).append("--").append(asyncFlowRequest.getReqTypeEnumMsg())
                .append("\n来源：").append(asyncFlowRequest.getSourceDes())
                .append("\n方法：").append(exeName)
                .append("\n单号：").append(serialid)
                .append("\n时间：").append(LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.NORM_DATETIME_PATTERN))
                .append("\n环境：").append(asyncFlowInfo.getEvn())
                .append("\n异常：").append(exception.toString())
                .append("\n位置：").append(Arrays.toString(exception.getStackTrace()));
        if (stringBuilder.toString().length() > 2048) {
            return stringBuilder.toString().substring(0, 2047);
        }

        return stringBuilder.toString();
    }

    @Data
    static class SendMsgReqRequest {

        //接收人工号，多个接收者用‘|’分隔，最多支持100个
        public String users;

        //内容，（企业微信最长不超过2048个字节，iOA最长不超过250个字）
        public String content;
    }

    @Data
    private static class SendBusinessAlarmRequest {

        //内容，（企业微信最长不超过2048个字节，iOA最长不超过250个字）
        private String AlarmMsg;
        //操作模块名称
        private String AsyncFlowModuleName;
        //操作节点名称
        private String AsyncFlowNodeName;
        //唯一号
        private String BusinessSerialId;
        //执行节点名
        private String ExecuteNodeName;
    }
}
